package cn.com.manager.controller.ueditor;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;

import cn.com.manager.controller.BaseController;
import cn.com.manager.pojo.UeditorUploadImage;
import cn.com.manager.utility.ApplicationConstants;
import cn.com.manager.utility.SystemUtils;

@Controller
@RequestMapping("/ueditor")
public class UeditorController extends BaseController{
	
	@RequestMapping("/controller")
	public void controller(@RequestParam("action")String action,HttpServletRequest request,HttpServletResponse response) throws Exception{
		if(StringUtils.equals("config", action)){
			String config = FileUtils.readFileToString(new File(servletContext.getRealPath("/js") + "/ueditor/config.json"));
			response.getWriter().println(config);
		}else if(StringUtils.equals("uploadimage", action)){
			if (request != null && request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> multipartFileList = multipartHttpServletRequest.getFiles("upfile");
                for (MultipartFile multipartFile : multipartFileList) {
                	String name = SystemUtils.newUploadFileName(multipartFile.getOriginalFilename());
        			String uploadPath = servletContext.getRealPath("/upload") + "/ueditor/" + name;
        			multipartFile.transferTo(new File(uploadPath));
        			UeditorUploadImage image = new UeditorUploadImage();
        			image.setState("SUCCESS");
        			image.setUrl(ApplicationConstants.IMG_WEB + request.getContextPath() + "/upload/ueditor/" + name);
        			image.setOriginal(multipartFile.getOriginalFilename());
        			image.setTitle(multipartFile.getOriginalFilename());
        			Gson gson = new Gson();
        			String json = gson.toJson(image);
        			response.getWriter().println(json);
                }
            }
		}
		
	}
	
}
